<template>
  <div class="scenic-like-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>
            <i class="icon-heart">❤️</i>
            我点赞的景点
          </h2>
          <div class="header-subtitle">发现精彩的旅行景点</div>
        </div>
        <div class="total-count">
          <span class="count-number">{{ totalLikes }}</span>
          <span class="count-text">条点赞</span>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">加载精彩内容中...</span>
    </div>

    <!-- 空状态 -->
    <div v-else-if="scenics.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="icon-empty">💭</i>
      </div>
      <h3 class="empty-title">还没有点赞的景点</h3>
      <p class="empty-description">快去发现那些精彩的旅行景点吧！</p>
      <router-link to="/homepage/scenic" class="explore-btn">
        <i class="icon-explore">🔍</i>
        探索景点
      </router-link>
    </div>

    <!-- 景点列表 -->
    <div v-else class="scenic-list">
      <div v-for="scenic in scenics" :key="scenic.scenicSpotId" class="scenic-card">
        <!-- 整个卡片可点击区域 -->
        <div class="card-clickable-area" @click="goToScenicDetail(scenic.scenicSpotId)">
          <!-- 图片容器 -->
          <div class="scenic-img-container">
            <img :src="scenic.mainImage" class="scenic-img" alt="景点图片" />
            <div class="image-overlay"></div>
            <div class="like-badge">
              <i class="badge-icon">❤️</i>
            </div>
          </div>
          
          <!-- 内容区域 -->
          <div class="scenic-content">
            <h3 class="scenic-title">{{ scenic.scenicAreaName }}</h3>
          </div>
        </div>

        <!-- 底部操作区 -->
        <div class="scenic-footer">
          
          <!-- 操作按钮 -->
          <div class="scenic-actions">
            <button class="like-btn active" @click.stop="handleCancelLike(scenic)">
              <i class="like-icon">❤️</i>
              <span>{{ scenic.likeCount }}</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div v-if="showPagination && scenics.length > 0" class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalLikes"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScenicLike',
  data() {
    return {
      scenics: [],
      loading: true,
      totalLikes: 0,
      currentPage: 1,
      pageSize: 8,
      showPagination: true,
      currentUserId: null,
      defaultImg: ""
    }
  },
  async created() {
    window.addEventListener('storage', this.handleStorageChange);
    await this.fetchLikedScenics();
  },
  beforeDestroy() {
    window.removeEventListener('storage', this.handleStorageChange);
  },
  methods: {
    formatTime(time) {
      if (!time) return '';
      return time.split('T')[0];
    },
    async fetchLikedScenics() {
      try {
        this.loading = true;
        const loginId = localStorage.getItem('loginId');
        const token = localStorage.getItem('token');
        if (!loginId) {
          this.scenics = [];
          this.totalLikes = 0;
          this.loading = false;
          return;
        }
        const userRes = await fetch(`http://localhost:8080/mw/UserByLoginId?loginId=${loginId}`);
        const userData = await userRes.json();
        this.currentUserId = userData.userId;
        if (!this.currentUserId) {
          this.scenics = [];
          this.totalLikes = 0;
          this.loading = false;
          return;
        }
        const likeRes = await fetch(`http://localhost:8080/sclike/listByUser?userId=${this.currentUserId}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Cache-Control': 'no-cache'
          }
        });
        const userLikes = await likeRes.json();
        this.totalLikes = userLikes.length;
        if (userLikes.length === 0) {
          this.scenics = [];
          this.loading = false;
          return;
        }

        this.scenics = await Promise.all(userLikes.map(async (like) => {
          let scenicAreaName = like.scenicAreaName || '未命名景点';
          let altitude = '未知';
          let scenicSpotLevel = '';
          if (!like.mainImage) {
            try {
              const scenicRes = await fetch(`http://localhost:8080/mw/detailVO/${like.scenicSpotId}`);
              if (scenicRes.ok) {
                const scenicData = await scenicRes.json();
                scenicAreaName = scenicData.detail?.scenicAreaName || scenicAreaName;
                altitude = scenicData.detail?.altitude || altitude;
                scenicSpotLevel = scenicData.detail?.scenicSpotLevel || scenicSpotLevel;
              }
            } catch (e) {
              console.error('获取景点详细信息失败:', e);
            }
          }
          
          let likeCount = 0;
          try {
            const likeCountRes = await fetch(`http://localhost:8080/sclike/countByScenicSpotId?scenicSpotId=${like.scenicSpotId}`);
            if (likeCountRes.ok) {
               likeCount = await likeCountRes.json();
            } else {
               console.warn(`获取景点 ${like.scenicSpotId} 点赞数失败:`, likeCountRes.status);
            }
          } catch (e) {
            console.error(`获取景点 ${like.scenicSpotId} 点赞数异常:`, e);
          }

          return {
            scenicSpotId: like.scenicSpotId,
            scenicAreaName: scenicAreaName,
            scenicSpotLevel: scenicSpotLevel,
            altitude: altitude,
            mainImage: like.mainImage,
            likeCount: likeCount
          };
        }));
      } catch (error) {
        console.error('获取点赞景点失败:', error);
        this.$message.error('获取点赞景点失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    handleCancelLike(scenic) {
      const { scenicSpotId } = scenic;
      if (!scenicSpotId) {
        console.error('取消点赞失败：scenicSpotId 为 undefined', scenic);
        this.$message.error('无效的景点ID');
        return;
      }
      this.cancelLike(scenicSpotId);
    },
    async cancelLike(scenicSpotId) {
      try {
        scenicSpotId = parseInt(scenicSpotId);
        if (isNaN(scenicSpotId) || !this.currentUserId) {
          console.error('取消点赞失败：无效的参数', {
            scenicSpotId,
            userId: this.currentUserId
          });
          this.$message.error('取消点赞失败：无效的参数');
          return;
        }
        const token = localStorage.getItem('token');
        const deleteRes = await fetch(
          `http://localhost:8080/sclike/deleteByUserAndScenic?userId=${this.currentUserId}&scenicSpotId=${scenicSpotId}`, 
          {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          }
        );
        if (!deleteRes.ok) {
          const errorText = await deleteRes.text();
          console.error('删除请求失败:', errorText);
          try {
            const errorData = JSON.parse(errorText);
            this.$message.error(`取消点赞失败: ${errorData.message || '未知错误'}`);
          } catch (parseError) {
            this.$message.error(`取消点赞失败: ${errorText}`);
          }
          return;
        }
        this.$message.success('取消点赞成功');
        await this.fetchLikedScenics();
      } catch (error) {
        console.error('取消点赞失败:', error);
        this.$message.error('取消点赞失败，请稍后重试');
      }
    },
    goToScenicDetail(scenicSpotId) {
      this.$router.push(`/homepage/scenic/${scenicSpotId}`);
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    handleStorageChange() {
      this.fetchLikedScenics();
    }
  }
}
</script>

<style scoped>
.scenic-like-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 32px;
}

.header-content {
  background: white;
  padding: 24px 32px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-heart {
  font-size: 24px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.header-subtitle {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.total-count {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(135deg, #a6a6e4 0%, #c3aadd 100%);
  color: white;
  padding: 16px 20px;
  border-radius: 12px;
  min-width: 80px;
}

.count-number {
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.count-text {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 4px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #abb7ec;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #6b7280;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 32px 0;
  line-height: 1.5;
}

.explore-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #f5f5f8 0%, #c4abdd 100%);
  color: white;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.explore-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

/* 景点列表 */
.scenic-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.scenic-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
}

.scenic-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-clickable-area {
  cursor: pointer;
}

.scenic-img-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.scenic-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.scenic-card:hover .scenic-img {
  transform: scale(1.1);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.3) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.scenic-card:hover .image-overlay {
  opacity: 1;
}

.like-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #e74c3c;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.badge-icon {
  font-size: 12px;
  animation: heartbeat 1.5s ease-in-out infinite;
}

@keyframes heartbeat {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.2); }
}

.scenic-content {
  padding: 20px;
}

.scenic-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.scenic-description {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.6;
  margin: 0 0 16px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.scenic-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #9ca3af;
}

.meta-icon {
  font-size: 14px;
}

.scenic-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e2e8f0;
}

.author-name {
  font-size: 14px;
  font-weight: 500;
  color: #4b5563;
}

.scenic-actions {
  display: flex;
  gap: 8px;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(238, 90, 36, 0.3);
}

.like-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(238, 90, 36, 0.5);
}

.like-btn.active {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

.like-icon {
  font-size: 14px;
  animation: like-pulse 0.6s ease-in-out;
}

@keyframes like-pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.3); }
}

/* 分页器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .scenic-like-container {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .scenic-list {
    grid-template-columns: 1fr;
  }
  
  .scenic-footer {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .header-content {
    padding: 20px;
  }
  
  .header-left h2 {
    font-size: 24px;
  }
  
  .scenic-content {
    padding: 16px;
  }
}
</style>